package cc.idoone.spring_boot_hello.h2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

/**
 * @auther hemj
 * @since 2017/9/24
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
		entityManagerFactoryRef = "entityManagerFactoryH2",
		transactionManagerRef = "h2JpaManager",
		basePackages = {"cc.idoone.spring_boot_hello.h2.jpa"}) //设置Repository所在位置
public class JpaStaffConfig {

	@Autowired
	@Qualifier("h2DataSource")
	private DataSource h2DataSource;

	@Bean(name = "entityManagerH2")
	public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
		return entityManagerFactoryH2(builder).getObject().createEntityManager();
	}

	@Bean(name = "entityManagerFactoryH2")
	public LocalContainerEntityManagerFactoryBean entityManagerFactoryH2(EntityManagerFactoryBuilder builder) {
		return builder
				.dataSource(h2DataSource)
				.properties(getVendorProperties(h2DataSource))
				.packages("cc.idoone.spring_boot_hello.h2.jpa") //设置实体类所在位置
				.persistenceUnit("h2PersistenceUnit")
				.build();
	}

	@Autowired
	private JpaProperties h2JpaProperties;


	private Map<String, String> getVendorProperties(DataSource dataSource) {
		return h2JpaProperties.getHibernateProperties(dataSource);
	}

	@Primary
	@Bean(name = "h2JpaManager")
	public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(entityManagerFactoryH2(builder).getObject());
	}

}
